﻿using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(SpriteBasic), true)]
public class SpriteBasicEditor : Editor
{
    public override void OnInspectorGUI()
    {
        EditorGUILayout.Space();
        serializedObject.Update();

        EditorGUI.BeginDisabledGroup(!ShouldDrawProperties());
        EditorGUI.EndDisabledGroup();

        DrawProperties();
        serializedObject.ApplyModifiedProperties();
    }

    protected bool ShouldDrawProperties()
    {
        GUILayout.BeginHorizontal();
        if (NGUIEditorTools.DrawPrefixButton("Atlas"))
        {
            ComponentSelector.Show<UIAtlas>(OnSelectAtlas);
        }

        NGUIEditorTools.DrawProperty("", serializedObject, "mAtlas", GUILayout.MinWidth(20f));
        GUILayout.EndHorizontal();
        return true;
    }

    void OnSelectAtlas(Object obj)
    {
        serializedObject.Update();
        SerializedProperty atlas = serializedObject.FindProperty("mAtlas");
        atlas.objectReferenceValue = obj;

        serializedObject.ApplyModifiedProperties();
        NGUITools.SetDirty(serializedObject.targetObject);
        NGUISettings.atlas = obj as UIAtlas;
    }
    
    protected void DrawProperties()
    {
        NGUIEditorTools.BeginContents(true);
        EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);

        if (NGUIEditorTools.DrawHeader("Sprite Details"))
        {
            SerializedObject obj = new SerializedObject(target); obj.Update();
            SerializedProperty atlas = obj.FindProperty("mAtlas");
            NGUIEditorTools.DrawSpriteField("Normal", obj, atlas, obj.FindProperty("normalSprite"));
            obj.ApplyModifiedProperties();

            NGUIEditorTools.DrawSpriteField("Disabled", serializedObject, atlas, serializedObject.FindProperty("disabledSprite"), true);
            NGUIEditorTools.DrawSpriteField("Activate", serializedObject, atlas, serializedObject.FindProperty("activateSprite"), true);
            NGUIEditorTools.DrawSpriteField("Click", serializedObject, atlas, serializedObject.FindProperty("clickSprite"), true);
        }
        EditorGUI.EndDisabledGroup();
        NGUIEditorTools.EndContents();
    }
}